//命名空间，公共变量放在这里
var KDDH = {
	isHaveRegisterHandler:false
};
$(function() {
//  localStorage.clear();
//  getTask_LocalStorage();
	KDDH.map = new AMap.Map('map', {
        resizeEnable: true
    });
//	KDDH.map.getUiSettings().setZoomControlsEnabled(true);
	KDDH.infoWindow = new AMap.InfoWindow({
        offset: new AMap.Pixel(0, -20)
    });
    var markerIcon = new AMap.Icon({
    	imageSize:[23,23],
//  	imageOffset:new AMap.Pixel(-50, 20),
    	image:"https://webapi.amap.com/theme/v1.3/markers/b/loc.png"
    })
    KDDH.locationMarker = new AMap.Marker({
    	icon:markerIcon,
    	offset: new AMap.Pixel(-12, -12)
    });
    KDDH.locationMarker.setMap(KDDH.map);
    //初始化滚动条
    initBar()
    //验证是否已登录
    checkUser();
    //调用安卓手机接口
	callAndroid();
	mySwiperFun();
	//点击masker遮罩层
	clickMasker()
	//关闭地址列表
	closeList();
	//打开地址列表
	openList();
	//地图放大缩小按钮
	mapZoom();
	//获取当前位置
	getLocation();
	//poi地址搜索
	poiPicker()
	
	function checkUser(){
//		showMSG();
		if(!sessionStorage.getItem("userId")){
			window.open("./login.html", "_self");
		}
//		sessionStorage.setItem("userId","1");
		if(sessionStorage.getItem('pageID') == 1){
			doCloseList();
		}else if(sessionStorage.getItem('pageID') == 2){
			doOpenList();
		}
	}
	
	function mySwiperFun() {
		var taskType;
		
		mySwiper = new Swiper('.swiper-container', {
			autoHeight: true,
			calculateHeight: true,
			observer: true, //修改swiper自己或子元素时，自动初始化swiper
			observeParents: true, //修改swiper的父元素时，自动初始化swiper
			onSlideChangeStart: function() {
				$(".tabBar a").removeClass('active');
				$(".tabBar a").eq(mySwiper.activeIndex).addClass('active');
			}
		});

		$(".tabBar li").on('click', function(e) {
			e.preventDefault();
			$(this).find('a').addClass('active');
			$(this).siblings().find('a').removeClass('active');
			mySwiper.slideTo($(this).index(), 500, false);
			taskType = $(this).attr("data-value");
		});
		$(".tabBar li").click(function(e) {
			e.preventDefault();
			if($(this).attr("data-value")=="1"){
				setTimeout(function(){
//		    		setNiceScroll(".tabcontainer .all .ulContent");
		    		setNiceScroll1(".tabcontainer .all .ulContent",".tabcontainer .all .ulContent ul");
		    	},200)
			}else if($(this).attr("data-value") == "2"){
				setTimeout(function(){
//		    		setNiceScroll(".tabcontainer .dcl .ulContent");
		    		setNiceScroll1(".tabcontainer .dcl .ulContent",".tabcontainer .dcl .ulContent ul");
		    	},200)
			}
		});
		if(taskType) {
			changeTaskType($(".taskType" + taskType));
		}
	}

	function changeTaskType(_this) {
		$(_this).find('a').addClass('active');
		$(_this).siblings().find('a').removeClass('active');
		mySwiper.slideTo($(_this).index(), 500, false);
	}
	
	//点击masker遮罩层
	function clickMasker() {
		$(".masker").on("click", function() {
			$(".infopanel").css('transform', 'translateY(7.72rem)');//上报面板隐藏
			$(this).hide();//遮罩层隐藏
		})
	}
	
	//关闭地址列表
	function closeList(){
		$(".zs_layout .addressList .closeBtn").click(function(e) {
			doCloseList();
		});
	}
	//打开地址列表
	function openList(){
		$(".zs_layout .addressListBtn .maptodoBT").click(function(e) {
			doOpenList();
		});
	}
	function doOpenList(){
		$(".addressList").show();
		sessionStorage.setItem('pageID', 2);
		setTimeout(function(){
    		initBar()
    	},200)
	}
	
	//地图放大缩小按钮
	function mapZoom() {
		$(".navBar #mapPlus").on("click",function(){
			KDDH.map.zoomIn();
		})
		$(".navBar #mapMinus").on("click",function(){
			KDDH.map.zoomOut();
		})
	}

	function getLocation() {
		$(".dingwei img").on("click",function(){
//			KDDH.refreshList();  //定位并刷新列表
			KDDH.map.setFitView();	//把地图缩放到数据范围
//			getScanCode();//二维码扫描测试
		})
	}
	
	//poi地址搜索
	function poiPicker(){
		AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
	        var poiPicker = new PoiPicker({
	            city:'北京',
	            input: 'pickerInput'
	        });
	        //初始化poiPicker
	        poiPickerReady(poiPicker);
	    });
	}
	function poiPickerReady(poiPicker) {
        window.poiPicker = poiPicker;
        var marker = new AMap.Marker();
        //选取了某个POI
        poiPicker.on('poiPicked', function(poiResult) {
            var source = poiResult.source,
                poi = poiResult.item,
                info = {
                    source: source,
                    id: poi.id,
                    name: poi.name,
                    location: poi.location.toString(),
                    address: poi.address
                };
            marker.setMap(KDDH.map);
            marker.setPosition(poi.location);
            KDDH.map.setZoomAndCenter(16, marker.getPosition());
            showInfoWindow(poi,info,marker);
        });
	}
	function showInfoWindow(poi,info,marker){
		var contentHtml = '<div class="infoContent">'
			+ '<h4>位置信息</h4>'
			+ '<ul><li><span>名称：</span><span class="pointName">'+info.name+'</span></li>'
			+ 	'<li><span>地址：</span><span class="pointAddress">'+info.address+'</span></li>'
			+ 	'<li><span>单号：</span><input type="text" class="courierNumber" placeholder="输入快递单号" /></li></ul>'
			+ '<input type="button" class="infoAddBtn" value="添加" data_location="'+info.location+'"/></div>';
		KDDH.infoWindow.setMap(KDDH.map);
        KDDH.infoWindow.setPosition(poi.location);
//      KDDH.infoWindow.setContent('POI信息: <pre>' + JSON.stringify(info, null, 2) + '</pre><input type="button" class="infoAddBtn" value="添加">');
        KDDH.infoWindow.setContent(contentHtml);
        KDDH.infoWindow.open(KDDH.map, marker.getPosition());
        
        setTimeout(function(){
        	$(".infoAddBtn").on("click",function(e){
        		var pointName = $(this).closest("div").find(".pointName").text();
        		var pointAddress = $(this).closest("div").find(".pointAddress").text();
        		var courierNumber = $(this).closest("div").find(".courierNumber").val();
        		var location = $(this).attr("data_location");
        		var lng = location.split(",")[0];
        		var lat = location.split(",")[1];
        		var jsonObj = {
					"name": pointName,
					"address": pointAddress,
					"couriernumber": courierNumber,//快递单号
					"lng": lng,
					"lat": lat,
					"userid": sessionStorage.getItem('userId')
				};
//				addNewTask_LocalStorage(jsonObj, function(result){
				var jsonStr = json2str(jsonObj);
        		callAjax(KddhBackUrl + "Address/addNewTask", jsonStr, function(result){
					console.log(result);
					KDDH.infoWindow.close();
					marker.setMap(null);
					if(result.msg=="success"){
						showMSG();
					}
					KDDH.refreshList();  //刷新列表
				});
	        })
        },100)
	}
	
	function showMSG(){
		$("#alertMSG").fadeIn(1000);
		setTimeout(function(){
			$("#alertMSG").fadeOut(1000);
		},1500)
	}
	
})

function doCloseList(){
	$(".addressList").hide();
	sessionStorage.setItem('pageID', 1);
}

//调用安卓手机接口
function callAndroid() {
	connectWebViewJavascriptBridge(function(bridge) {
		//监听返回键导航
		bridge.registerHandler("navCtrl", function(data, responseCallback) {
			//自行控制导航
//			var msg = confirm("是否要清除缓存？");
//			if(msg == true) {
//				getInfoFromWebView("clearCache");//清除缓存
//			}
//			getInfoFromWebView("closeApp");//退出系统
			
			if(sessionStorage.getItem('pageID') == 2){
				doCloseList();
			}else{
				getInfoFromWebView("clearCache");//清除缓存
				getInfoFromWebView("closeApp");//退出系统
			}
		});
	})
}
//添加新建警情点
function createJQWithLocation(lng,lat){
//	alert(lng+","+lat);
	var lnglat=new AMap.LngLat(lng,lat);
	AMap.convertFrom(lnglat,"gps",function(status,result){
		console.log(result.locations[0]);
		KDDH.currentPosition = result.locations[0];
//		KDDH.map.setCenter(KDDH.currentPosition)
    	KDDH.locationMarker.setPosition(KDDH.currentPosition);
    	KDDH.isRefreshLocation = true;
	})
}

function getScanCode(){
	getInfoFromWebView("getScanCode");//调用扫面二维码
}
